/**
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: ---Technology Co. Ltd</p>
 * <p>2014-4-30</p>
 * @author Jan.Zhang
 */
package com.xianl.busiplat.shiro;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import com.xianl.busiplat.exception.AccountLoseException;
import com.xianl.busiplat.exception.IncorrectCaptchaException;
import com.xianl.busiplat.po.RolePermission;
import com.xianl.busiplat.po.User;
import com.xianl.busiplat.po.UserRole;
import com.xianl.busiplat.service.UserRoleService;
import com.xianl.busiplat.service.UserService;
import com.xianl.busiplat.springside.Digests;
import com.xianl.busiplat.springside.Encodes;


/** 
 * desc:
 * <p>author: Jan.Zhang </p>
 * date: 2014-4-30
 */
public class ShiroDbRealm extends AuthorizingRealm {
	
	private static final int INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;
	private static final String ALGORITHM = "SHA-1";
	
	protected UserService userService;
	
	protected UserRoleService userRoleService;
	
	public ShiroDbRealm() {
		super();
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM);
		matcher.setHashIterations(INTERATIONS);

		setCredentialsMatcher(matcher);
	}

	/* 
	 * desc:
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName()).iterator().next();
		List<UserRole> userRoles = userRoleService.find(shiroUser.getId());
		shiroUser.getUser().setUserRoles(userRoles);
		
		if (!userRoles.isEmpty()) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (UserRole userRole : userRoles) {
				for(RolePermission p  : userRole.getPermissions())
					info.addStringPermission(p.getPermission());
			}
			return info;
		} else {
			return null;
		}
	}

	/* 
	 * desc:
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
		String parm = token.getCaptcha();
		String c = (String) SecurityUtils.getSubject().getSession().getAttribute(SimpleCaptchaServlet.CAPTCHA_KEY);
		if(!parm.equalsIgnoreCase(c) ) {
			throw new IncorrectCaptchaException("验证码错误！");
		}
		User user = userService.get(token.getUsername());
		if(user != null ) {
			if(user.getStatus() == 1 ) {
				throw new DisabledAccountException();
			}
			if(user.getLoseDate().after(new Date()) && user.getEffDate().before(new Date()) ) {
				byte[] salt = Encodes.decodeHex(user.getSalt());
				ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUsername(), user);
				return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), ByteSource.Util.bytes(salt), getName());
			} else {
				throw new AccountLoseException();
			}
		} else {
			return null;
		}
	}
	
	public static class HashPassword {
		public String salt;
		public String password;
	}
	
	public HashPassword encrypt(String plainText) {
		HashPassword result = new HashPassword();
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		result.salt = Encodes.encodeHex(salt);

		byte[] hashPassword = Digests.sha1(plainText.getBytes(), salt, INTERATIONS);
		result.password = Encodes.encodeHex(hashPassword);
		return result;
	}
	
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	
	/**
	 * desc: clear User cache authorization
	 * <p>author：Jan.Zhang </p>
	 *  date : 2014-4-30 
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}
	
	
	/**
	 * @param userService the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	
	/**
	 * @param userRoleService the userRoleService to set
	 */
	public void setUserRoleService(UserRoleService userRoleService) {
		this.userRoleService = userRoleService;
	}

	public static class ShiroUser implements Serializable {

		/**
		 * long:serialVersionUID
		 */
		private static final long serialVersionUID = -3429128922453333833L;
		private int id;
		private String loginName;
		private User user;

		public ShiroUser () {
		}

		public ShiroUser (int id , String loginName , User user ) {
			this.id = id;
			this.loginName = loginName;
			this.user = user;
		}
		
		/**
		 * @return the id
		 */
		public int getId() {
			return id;
		}

		public String getLoginName() {
			return loginName;
		}

		public User getUser() {
			return user;
		}

		/**
		 */
		@Override
		public String toString() {
			return loginName;
		}
	}
}
